<?php
Class Media{
public static function GenerateBackButton($dirct){
		$dirs = array();
		$folder_arr = explode('/',$dirct);
				$count_folder = count($folder_arr);
				unset($folder_arr[$count_folder-1]);
				$back = implode('/',$folder_arr);
				$back = str_replace(DOCUMENT_ROOT."/upload", "", $back);
				$back = trim($back,'/');
				$form = "<form action='/admin/media.html' method='POST'><input type='hidden' name='back' value='".$back."' />";
				$dirs['img'] = "<img src='/public/images/admin/icons/folder.png' border='0' width='50px' />";
				$dirs['name'] = $form."<input class='folder_bottom' align='left' type='submit' value='Назад'/></form>";
	return $dirs;
}

public static function delete_directory($dirname) {
 if (is_dir($dirname))
 $dir_handle = opendir($dirname);

 if (!$dir_handle){
    return false;
 }
     while($file = readdir($dir_handle)) {
         if ($file != "." && $file != "..") {
             if (!is_dir($dirname."/".$file)){
                unlink($dirname."/".$file);
             }else{
                Media::delete_directory($dirname.'/'.$file);
             }
         }
     }

 closedir($dir_handle);
 rmdir($dirname);

 return true;
}
public static function Operations(){
    $request = getRequest::getInstance();
    $type = $request->getVar('type', 'GET');
    $path = $request->getVar('path', 'GET');

    $dirct = DOCUMENT_ROOT."/upload";

    $acl = new Df_acl;
    $acl->SetAclTableName("acl");
    //Читаем ID групу пользователя
    $role = Df_Auth::read("role");
    $acl->addRole($role);
    $acl->add_Resource("Media");
    //Доступ к файловом менеджеру
    $acl->add_access("1");
    $access = array();
    $access['allow'] = $acl->allow();
    //Права на загрузку файлов, создание директорий
    $acl->add_access("2");
    $access['allow_write'] = $acl->allow();
    //Права на удаление файлов, директорий
    $acl->add_access("3");
    $access['allow_delete'] = $acl->allow();

	if(!empty($type) && !empty($path) && $type=='del' && file_exists($dirct.$path) && !is_dir($dirct.$path)){
	//Удаляем файл
            if($access['allow_delete']==true)unlink($dirct.$path);
	}elseif(!empty($type) && !empty($path) && $type=='del' && file_exists($dirct.$path) && is_dir($dirct.$path)){
        //Удаляем директорию
             if($access['allow_delete']==true)Media::delete_directory($dirct.$path);
	}elseif(!empty($type) && !empty($path) && $type=='create'){
            $path = trim($path,'/');
            if($access['allow_write']==true){
                mkdir($dirct."/".$path);
                chmod($dirct."/".$path, 0777);
            }
	}elseif(!empty($_FILES)){
            if($access['allow_write']==true){
                $path = $request->getVar('path', 'POST');
                    if(empty($path)){$path="/";}else{$path = $path."/";}

                $uploadfile = $dirct.$path.basename($_FILES['uploadfile']['name']);
                //Загружаем файл
                move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile);
                $type_load = $request->getVar('type', 0, 'post', 'string');
                //Роспаковываем архив
                    if($type_load=='unzip'){
                            Media::unzip($uploadfile, $path);
                    }
            }
	}
}

public static function unzip($file, $newLocation){
	$file = str_replace("//","/",$file);
	$newLocation = str_replace("//","/",$newLocation);
	$newLocation = DOCUMENT_ROOT."/upload".$newLocation;

    if(function_exists('exec')){
        exec("unzip ".$file." -d ".$newLocation, $array);
	unlink($file);
    }else{
        require_once(PLUGINS_PATH.'/pclzip.lib.php');
        $archive = new PclZip($file);
        $archive->extract(PCLZIP_OPT_PATH, $newLocation);
        unset($archive);
        unlink($file);
    }
}

public static function Manager(){
    $acl = new Df_acl;
    $acl->SetAclTableName("acl");
    //Читаем ID групу пользователя
    $role = Df_Auth::read("role");
    $acl->addRole($role);
    $acl->add_Resource("Media");
    //Доступ к файловом менеджеру
    $acl->add_access("1");
    $access = array();
    $access['allow'] = $acl->allow();
    //Права на загрузку файлов, создание директорий
    $acl->add_access("2");
    $access['allow_write'] = $acl->allow();
    //Права на удаление файлов, директорий
    $acl->add_access("3");
    $access['allow_delete'] = $acl->allow();

   $result = array();
			if($access['allow'] == true){
					$i=1;
					$dirs = array();
					$files = array();
					$request = getRequest::getInstance();
					$folder = $request->getVar('folder','POST');
					$back = $request->getVar('back', 'POST');

					if(!empty($folder)){
						$dirct = DOCUMENT_ROOT."/upload".$folder;
						$dirct = rtrim($dirct,'/');
						$dirs[$i] = Media::GenerateBackButton($dirct);

						$i++;

					}elseif(!empty($back)){
						$dirct = $back;
						$dirct = trim($dirct,'/');
						$dirct = DOCUMENT_ROOT."/upload/".$dirct;
						$dirct = rtrim($dirct,'/');
						$folder = "/".$back;
						if($dirct!=DOCUMENT_ROOT."/upload"){
							$dirs[$i] = Media::GenerateBackButton($dirct);
							$i++;
						}
					}else{
						$dirct = DOCUMENT_ROOT."/upload";
						$folder = "/";
					}
				$hdl=opendir($dirct);

					while ($file = readdir($hdl))
						{
						if (($file!="..")&&($file!="."))
							{
								$full = $dirct."/".$file;
								$path=str_replace(DOCUMENT_ROOT."/upload", "", $full);
								if(is_dir($full)==True)
								{
                                                                        $form = "<form action='/admin/media.html' method='POST'><input type='hidden' name='folder' value='".$path."' />";
									$dirs[$i]['img'] = "<img src='/public/images/admin/icons/folder.png' border='0' width='50px' />";
									$dirs[$i]['name'] = $form."<input class='folder_bottom' align='left' type='submit' value='".$file."'/></form>";
									$dirs[$i]['path'] = $path;
								}else{
									$ext = pathinfo($file, PATHINFO_EXTENSION);
									if($ext == "jpeg"||$ext == "jpe"||$ext == "jpg"||$ext == "gif"||$ext == "png"||$ext == "xls"|$ext == "txt"||$ext == "doc"||$ext == "pdf"||$ext == "wav"||$ext == "mid"||$ext == "ogg"||$ext == "mp3"||$ext == "zip"){
                                                                            $format = $ext.".gif";
                                                                        }else{
                                                                            $format = "unk.gif";
                                                                        }
										$files[$i]['img'] = "<img src='/public/images/admin/icons/file_format/".$format."' border='0' width='35px' />";
										$files[$i]['name'] = $file;
										$files[$i]['s'] = filesize($full)/1000;
										$files[$i]['path'] = $path;
								}
							}
							$i++;
						 }
					closedir($hdl);

						$i = 0;
						foreach($dirs as $val){
							$result[$i] = $val;
							$i++;
						}
						foreach($files as $val){
							$result[$i] = $val;
							$i++;
						}
                                               
				}
  return array('result'=>$result, 'access'=>$access, 'folder'=>$folder);
}
}